package cn.tedu.toa.management.sys.service.impl;

import cn.tedu.toa.management.sys.entity.SysUsers;
import cn.tedu.toa.management.sys.mapper.SysRolesMapper;
import cn.tedu.toa.management.sys.mapper.SysUsersMapper;
import cn.tedu.toa.management.sys.service.SysUsersService;
import cn.tedu.toa.management.sys.service.ex.*;
import cn.tedu.toa.management.sys.vo.UserVo;
import cn.tedu.toa.management.util.UserUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author huaqian
 * @since 2021-09-09
 */
@Service
public class SysUsersServiceImpl extends ServiceImpl<SysUsersMapper, SysUsers> implements SysUsersService {

        @Autowired
        private SysUsersMapper sysUsersMapper;

        @Autowired
        private SysRolesMapper sysRolesMapper;

    @Override
    public PageInfo<SysUsers> findUserList(String username, Integer pageNum, Integer pageSize) {
        //1 参数验证
        if(pageNum==null || pageSize==null || pageSize<1 ){
            throw new ParamIllegelException("用户列表查询异常!查询的分页参数不合法!");
        }
        //pageHelp分页
        PageHelper.startPage(pageNum,pageSize);
        //调用持久层
        List<SysUsers> list=sysUsersMapper.selectUserList(username);
        //查询结果存入PageInfo
        return new PageInfo<>(list);

    }

    @Override
    @Transactional
    public void saveUser(SysUsers user, Integer[] roleIds) {
        //对user进行非空判断 密码是否存在
        if(user==null||
                StringUtils.isEmpty(user.getUsername())
                || StringUtils.isEmpty(user.getPassword() )
        ){
                throw new ParamIllegelException("添加用户异常,提那家用户信息不合法!");
        }
        //判断用户名是否被暂用
        SysUsers users=sysUsersMapper.selectUserByName(user.getUsername());
        if(users!=null){
            throw new UserNameIsUsedException("添加用户名存在!该用户名已经存在!");
        }
        //对roleIds的长度是否为0  0 是异常
        if(roleIds==null || roleIds.length==0){
            throw new RoleNotChoosedException("添加用户失败!该用户没有选择角色!");
        }
        //判断roleIds中的角色是否存在
        int count=sysRolesMapper.selectRoleCount(roleIds);
        if(count!=roleIds.length){
            throw new RecordNotFoundException("添加用户失败!拟添加的角色不存在!");
        }
        //补全处理数据  密码加密和 对valid  创建人创建时间
        //对象加密和盐值
        String salt= UUID.randomUUID().toString();
        String pwdHex= encryPwd(user.getPassword(),salt);
        user.setValid(1).setPassword(pwdHex).setSalt(salt)
                .setCreatedTime(LocalDateTime.now()).setCreatedUser(UserUtils.getCurrentUserName())
                .setModifiedTime(LocalDateTime.now()).setModifiedUser(UserUtils.getCurrentUserName());
        //添加用户 并获取用户id
        int row=sysUsersMapper.insert(user);
        if(row!=1){
            throw new InsertException("添加用户失败!");
        }
        //添加用户角色表 user 添加后 userId自动会赋值
         row=sysUsersMapper.insertUserRoles(user.getId(),roleIds);
        if(row!=roleIds.length){
            throw new InsertException("添加用户失败!建立用户角色关系失败!");
        }

    }

//    //加密方法  设置  加密 和盐值
//    private SysUsers encryPwd(SysUsers user){
//        String salt= UUID.randomUUID().toString();
//        SimpleHash sh= new SimpleHash("MD5",user.getPassword(),salt,3);
//        String pwdHex=sh.toHex();
//        user.setPassword(pwdHex).setSalt(salt);
//        return user;
//    }

    //加密方法  设置  加密 和盐值
    private String encryPwd(String password,String salt){
        SimpleHash sh= new SimpleHash("MD5",password,salt,3);
        return sh.toHex();
    }

    @Override
    @Transactional
    public void updateUser(SysUsers user, Integer[] roleIds) {
        //查询用户是否存在 不存在抛异常
        if(user==null|| user.getUsername()==null){
            throw new ParamIllegelException("修改用户异常!用户不为空!");
        }
        SysUsers users=sysUsersMapper.selectById(user.getId());
        if(users==null){
            throw new RecordNotFoundException("修改用户异常!用户不存在!");
        }
        //用户名重名判断
        int count=sysUsersMapper.checkUserName(user.getId(),user.getUsername());
        if(count!=0){
            throw new UserNameIsUsedException("修改用户异常!用户名已经被使用!");
        }
        //查询roleIds是否存在  不存在抛异常
         count=sysRolesMapper.selectRoleCount(roleIds);
        if(count!=roleIds.length){
            throw new RecordNotFoundException("修改用户异常!角色id不合法!");
        }
        //更新user表 先组装
        //判断密码是否有空,为空则密码不变
        if(user.getPassword()==null){
            user.setPassword(users.getPassword()).setSalt(users.getSalt());
        }else{
            //加密和盐值
            String salt= UUID.randomUUID().toString();
            String pwdHex= encryPwd(user.getPassword(),salt);
            user.setPassword(pwdHex).setSalt(salt);
        }
        user.setModifiedTime(LocalDateTime.now()).setModifiedUser(UserUtils.getCurrentUserName())
        .setValid(users.getValid());
        int row=sysUsersMapper.updateById(user);
        if(row!=1){
            throw new UpdateException("修改用户异常!");
        }
        //更新userroel表
        //先删除  在插入
         row=sysUsersMapper.delUserRoleByUserId(user.getId());
         row=sysUsersMapper.insertUserRoles(user.getId(),roleIds);
         if(row!=roleIds.length){
             throw new InsertException("修改用户异常!添加用户角色关联系异常!");
         }
    }

    @Override
    public void modifyUserValidByUserId(Integer userId,Integer valid) {

        int row=sysUsersMapper.modifyUserValidByUserId(userId, valid);
        if(row!=1){
            throw new UpdateException("修改用户状态异常!");
        }
    }

    @Override
    public UserVo selectUserByUserId(int userId) {
        if(userId<=0){
            throw new ParamIllegelException("修改用户异常!查询的用户名为空!");
        }
        SysUsers user=sysUsersMapper.selectById(userId);
        if(user==null){
            throw new RecordNotFoundException("修改用户异常!查询的用户名不存在!");
        }
        List<Integer> roldIds=sysUsersMapper.selectUserRoleByuserId(user.getId());
        UserVo userVo= new UserVo().setUsername(user.getUsername())
                                    .setPassword(user.getPassword())
                                    .setEmail(user.getEmail())
                                    .setMobile(user.getMobile())
                                    .setRoleIds(roldIds);
        return userVo;
    }

    @Override
    public void updatePwd(String password, String newPassword) {
        //先确认用户密码是否正确
        Subject subject= SecurityUtils.getSubject();
        SysUsers users= (SysUsers) subject.getPrincipal();
        if(users==null){
            throw new UnknownAccountException("登录超时,请重新登录!");
        }
        //验证password是否正确
        String pwdHex=encryPwd(password,users.getSalt());
        if(!pwdHex.equals(users.getPassword())){
            throw  new UpdateException("原密码错误!");
        }
        //更新新的密码 和盐值
        String salt= UUID.randomUUID().toString();
        pwdHex= encryPwd(newPassword,salt);
        int num=sysUsersMapper.updatePwdByUserId(pwdHex,salt,users.getId());
        if(num!=1){
            throw  new UpdateException("修改密码异常!");
        }
    }
}
